from fastapi import FastAPI, Request, Form, Query
from fastapi.responses import HTMLResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from fastapi.middleware.cors import CORSMiddleware
import uvicorn
import os
from dotenv import load_dotenv
import time
from typing import Optional

# 导入股票预测系统
from modules.search_engine import StockSearchEngine
from modules.stock_data import StockDataFetcher
from modules.ai_analyzer import AIAnalyzer

# 加载环境变量
load_dotenv()

app = FastAPI(title="股票预测系统")

# 挂载静态文件目录
app.mount("/static", StaticFiles(directory="static"), name="static")

# 设置模板目录
templates = Jinja2Templates(directory="templates")

# 添加CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 初始化组件
try:
    search_engine = StockSearchEngine()
    data_fetcher = StockDataFetcher()
    ai_analyzer = AIAnalyzer()
    system_ready = True
except Exception as e:
    print(f"初始化系统组件失败: {str(e)}")
    print("请检查您的API密钥和网络连接。")
    search_engine = None
    data_fetcher = None
    ai_analyzer = None
    system_ready = False

@app.get("/", response_class=HTMLResponse)
async def index(request: Request):
    """
    返回主页
    """
    return templates.TemplateResponse("index.html", {"request": request})

@app.get("/api/search")
async def search(query: str = Query("", description="股票名称或代码")):
    """
    搜索股票信息
    """
    if not query:
        return {"results": []}

    # 模拟搜索延迟
    time.sleep(0.5)

    # 解析查询，假设格式为"股票名称 股票代码"或单独的名称/代码
    parts = query.split()
    if len(parts) >= 2:
        stock_name = parts[0]
        stock_code = parts[1].strip("()")
    else:
        stock_name = query
        stock_code = query

    # 使用搜索引擎获取股票信息
    try:
        if search_engine:
            search_results = search_engine.search_stock_info(stock_code, stock_name, days=30)
            # 转换为前端可用的格式
            formatted_results = []
            for item in search_results:
                formatted_results.append({
                    "title": f"{item.get('title', '未知标题')}",
                    "description": item.get('snippet', '无描述'),
                    "url": item.get('url', '#'),
                    "source": item.get('source', '来源'),
                    "date": item.get('date', '日期')
                })
            return {"results": formatted_results}
        else:
            return {"results": [], "error": "搜索引擎未初始化"}
    except Exception as e:
        return {"results": [], "error": str(e)}

@app.post("/api/predict")
async def predict_stock(stock_code: str = Form(...), stock_name: str = Form(...)):
    """
    预测股票走势
    """
    if not system_ready:
        return JSONResponse(
            status_code=500,
            content={"error": "预测系统未初始化，请检查API密钥和网络连接"}
        )

    try:
        # 获取股票基本面信息
        fundamental_info = search_engine.search_stock_info(stock_code, stock_name, days=30)

        # 获取股票历史数据
        historical_data = data_fetcher.fetch_stock_data(stock_code)

        # 分析基本面信息
        fundamental_analysis = ai_analyzer.analyze_fundamental_data(stock_code, stock_name, fundamental_info)

        # 分析技术面数据
        technical_analysis = ai_analyzer.analyze_technical_data(stock_code, stock_name, historical_data)

        # 生成最终预测
        prediction = ai_analyzer.generate_final_prediction(stock_code, stock_name, fundamental_analysis, technical_analysis)

        # 构建结果
        result = {
            "stock_info": {
                "code": stock_code,
                "name": stock_name
            },
            "fundamental_analysis": fundamental_analysis,
            "technical_analysis": technical_analysis,
            "final_prediction": prediction,
            "timestamp": time.strftime("%Y-%m-%d %H:%M:%S")
        }

        # 添加结果摘要
        from modules.result_summary import generate_summary
        generate_summary(result)

        # 保存结果
        output_file = f"stock_analysis_{stock_code}.json"
        with open(output_file, "w", encoding="utf-8") as f:
            import json
            json.dump(result, f, ensure_ascii=False, indent=2)

        return result
    except Exception as e:
        return JSONResponse(
            status_code=500,
            content={"error": f"预测失败: {str(e)}"}
        )

@app.get("/api/check-status")
async def check_status():
    """
    检查系统状态
    """
    anspire_api_key = os.getenv("ANSPIRE_API_KEY")
    deepseek_api_key = os.getenv("DEEPSEEK_API_KEY")
    qwen_api_key = os.getenv("QWEN_API_KEY")

    return {
        "system_ready": system_ready,
        "search_engine_ready": search_engine is not None,
        "data_fetcher_ready": data_fetcher is not None,
        "ai_analyzer_ready": ai_analyzer is not None,
        "anspire_api_configured": bool(anspire_api_key),
        "deepseek_api_configured": bool(deepseek_api_key),
        "qwen_api_configured": bool(qwen_api_key)
    }

if __name__ == "__main__":
    uvicorn.run("main:app", host="127.0.0.1", port=8040, reload=True)
